# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _, tools
from odoo.addons.fapiao_base.models.fapiao_paper import INVOIVCE_TYPE_SELECTION

import datetime


class FapiaoPaper(models.Model):
    _inherit = "fp.fapiao.paper"

    invoice_ids = fields.One2many(
        'fp.input.inv', 'paper_id',
        help='从input.inv创建paper, 用于反向设置paper_id')


class InputInvoice(models.Model):
    _name = "fp.input.inv"
    _description = "Fapiao Invoice"
    _order = 'time_fapiao desc, id desc'

    name = fields.Char(
        string='Fapiao Name', required=True, copy=False, readonly=True,
        states={'draft': [('readonly', False)]}, index=True,
        default=lambda self: _('New'),
        help="系统管理用")

    paper_id = fields.Many2one(
        'fp.fapiao.paper', string='Related Fapiao Paper',
        required=False, readonly=True, index=True,
        help='')

    state = fields.Selection(selection=[
        ('draft', 'Draft'),
        ('confirmed', 'Confirmed'),
        ('done', 'Done'),  # 发票的正常稳定状态
        ('posted', 'Posted'),
        ('cancel', 'Cancelled'),
    ], string='Status', required=True, readonly=True, copy=False, default='draft',
        help="系统管理用")

    type = fields.Selection(
        selection=[
            ('out_invoice', '销项蓝票'),
            ('out_refund', '销项红票'),
        ], string='Type',
        required=True, index=True, readonly=False,
        default='out_invoice',
        help="系统管理用")

    attachment_id = fields.Many2one(related='paper_id.attachment_id')

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company,
        help="系统管理用")

    user_id = fields.Many2one(
        'res.users', string='User', index=True, default=lambda self: self.env.user)

    invoice_type = fields.Selection(
        selection=INVOIVCE_TYPE_SELECTION, string='Fapiao Type', default='vat_general_e',
        help="票面信息")

    time_fapiao = fields.Datetime(
        string='Fapiao Time', index=True, copy=False,
        default=fields.Datetime.now,
        help="销项票使用, 开票时间")

    note = fields.Text(string='Description', help="备注")

    date_fapiao = fields.Date(related='paper_id.date_fapiao')
    invoice_code = fields.Char(related='paper_id.invoice_code')
    invoice_number = fields.Char(related='paper_id.invoice_number')
    check_code = fields.Char(related='paper_id.check_code')

    taxmachine_code = fields.Char(related='paper_id.taxmachine_code')
    payee_name = fields.Char(related='paper_id.payee_name')
    checker_name = fields.Char(related='paper_id.checker_name')
    drawer_name = fields.Char(related='paper_id.drawer_name')

    amount_untaxed = fields.Float(
        string='Untaxed Amount', compute='_amount_all', store=True)
    amount_tax = fields.Float(string='Tax', compute='_amount_all', store=True)
    amount_total = fields.Float(
        string='Total', compute='_amount_all', store=True)

    cn_amount_total = fields.Char(string='CN Total')

    @api.depends('line_ids.amount_total')
    def _amount_all(self):
        for one in self:
            amount_untaxed = amount_tax = 0.0
            discount_untaxed = discount_tax = 0.0
            for line in one.line_ids:
                amount_untaxed += line.amount_untaxed
                amount_tax += line.amount_tax
                discount_untaxed += line.amount_untaxed_discount
                discount_tax += line.amount_tax_discount

            amount_untaxed = round(amount_untaxed + discount_untaxed, 2)
            amount_tax = round(amount_tax + discount_tax, 2)

            one.update({
                'amount_untaxed': amount_untaxed,
                'amount_tax': amount_tax,
                'amount_total': round(amount_untaxed + amount_tax, 2)
            })

    company_partner_id = fields.Many2one(
        'fp.partner', string='Company Partner',
        compute='_compute_company_partner',
        help="公司开票信息")

    partner_id = fields.Many2one(
        'fp.partner', string='Partner',
        index=True, readonly=True,
        states={'draft': [('readonly', False)]},
        help="票面的购买方,即客户信息")

    company_name = fields.Char(
        'Company Name', compute='_compute_company_partner')
    company_tin = fields.Char(
        'Company TIN', compute='_compute_company_partner')
    company_address = fields.Char(
        'Company Address', compute='_compute_company_partner')
    company_phone = fields.Char(
        'Company Phone', compute='_compute_company_partner')
    company_bank_name = fields.Char(
        'Company Bank Name', compute='_compute_company_partner')
    company_acc_number = fields.Char(
        string='Company Bank Account', compute='_compute_company_partner')

    company_address_phone = fields.Char(
        string='Company Address Phone', compute='_compute_company_partner')
    company_bank_account = fields.Char(
        string='Company Bank And Account', compute='_compute_company_partner')

    @api.depends('company_id')
    def _compute_company_partner(self):
        for one in self:
            comp_partner = one.company_id._get_fp_partner()

            one.company_partner_id = comp_partner
            one.company_name = comp_partner.fapiao_name
            one.company_tin = comp_partner.tin
            one.company_address = comp_partner.address
            one.company_phone = comp_partner.phone
            one.company_bank_name = comp_partner.bank_name
            one.company_acc_number = comp_partner.acc_number
            one.company_address_phone = comp_partner.address_phone
            one.company_bank_account = comp_partner.bank_account

    partner_name = fields.Char(
        string='Partner Name', related='partner_id.fapiao_name')
    partner_tin = fields.Char(
        string='Partner TIN', related='partner_id.tin')
    partner_address = fields.Char(
        string='Partner Address', related='partner_id.address')
    partner_phone = fields.Char(
        string='Partner Phone', related='partner_id.phone')
    partner_bank_name = fields.Char(
        string='Partner Bank Name', related='partner_id.bank_name')
    partner_acc_number = fields.Char(
        string='Partner Bank Account', related='partner_id.acc_number')

    partner_address_phone = fields.Char(
        string='Partner Address Phone', related='partner_id.address_phone')
    partner_bank_account = fields.Char(
        string='Partner Bank And Account', related='partner_id.bank_account')

    line_ids = fields.One2many(
        'fp.input.inv.line', 'fapiao_id', string='Fapiao Lines',
        states={'cancel': [('readonly', True)], 'done': [('readonly', True)]},
        copy=True, auto_join=True)

    # paper_ids = fields.Many2many(
    #     'fp.fapiao.paper', string='Fapiao Papers',
    #     compute='_compute_paper_ids', help='')

    # @api.depends('line_ids', 'line_ids.paper_line_id', 'line_ids.discount_paper_line_id')
    # def _compute_paper_ids(self):
    #     for order in self:
    #         paper_lines = self.env['fp.fapiao.paper.line']

    #         pl = order.line_ids.mapped('paper_line_id')
    #         dpl = order.line_ids.mapped('discount_paper_line_id')
    #         paper_lines = paper_lines | pl | dpl
    #         papers = paper_lines.mapped('fapiao_id')
    #         order.paper_ids = papers

    def _update_name(self):
        for one in self:
            if not one.name or one.name == _('New'):
                now = datetime.datetime.now()
                now1 = now.strftime('%Y%m%d')
                one.name = now1 + str(one.id).rjust(12, '0')

    @api.model_create_multi
    def create(self, vals_list):
        records = super().create(vals_list)
        records._update_name()

        return records

    #
    # Actions
    #

    def action_confirm(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'draft')])
        for one in self2:
            one.write({'state': 'confirmed'})

    def action_cancel(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])

        for one in self2:
            one.write({'state': 'cancel'})

    def action_draft(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'cancel')])
        for one in self2:
            one.write({'state': 'draft'})

    # def action_post(self):
    #     # call ERP 接口 反写 财务模块的 会计凭证
    #     self.write({'state': 'posted'})

    def action_to_paper(self):
        self2 = self.search(
            [('id', 'in', self.ids), ('state', '=', 'confirmed')])

        paper_vals_list = []

        for one in self2:
            if one.paper_id:
                continue

            line_vals_list = one.line_ids._vals_list_for_paper()
            line_tuples = [(0, 0, line_vals)
                           for line_vals in line_vals_list]

            fpuser = one.user_id._get_fp_user()

            vals = {
                'state': 'confirmed',
                'type': one.type,
                'company_id': one.company_id.id,
                'user_id': one.user_id.id,
                'invoice_type': one.invoice_type,
                'time_fapiao': one.time_fapiao,
                'date_fapiao': one.time_fapiao,
                'note': one.note,

                'taxmachine_code': fpuser.taxmachine_code,
                'payee_name': fpuser.payee_name,
                'checker_name': fpuser.checker_name,
                'drawer_name': fpuser.drawer_name,

                'amount_untaxed': one.amount_untaxed,
                'amount_tax': one.amount_tax,
                'amount_total': one.amount_total,
                'cn_amount_total': one.cn_amount_total,

                'saler_id': one.company_partner_id.id,
                'buyer_id': one.partner_id.id,
                'line_ids': line_tuples,
                'invoice_ids': [(5, 0, 0), (4, one.id, 0)]
            }

            paper_vals_list.append(vals)

        print('action_to_paper, ', paper_vals_list)

        return self.env['fp.fapiao.paper'].create(paper_vals_list)
